package com.googlecode.mbhsrobopro.controller.components;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class DynamicGraph extends JFrame {

	public static ArrayList<Point.Double> values;
	private static final int WIDTH = 1024, HEIGHT = 768; 
	private static final int DELAY = 100;
	private double xStep, yStep, xMax, yMax; // xMin = yMin = 0 (cuz I'm Lay-Z)
	private MyPanel panel;

	public DynamicGraph(double xMax, double yMax, double xStep, double yStep) {
		this.xMax = xMax;
		this.yMax = yMax;
		this.xStep = xStep;
		this.yStep = yStep;
		values = new ArrayList<Point.Double>();
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		panel = new MyPanel();
		setBackground(Color.white);
		panel.setBackground(Color.white);
		add(panel);
		setPreferredSize(new Dimension(WIDTH, HEIGHT));
		pack();
		setVisible(true);
		new Thread() {
			public void run() {
				while(true) {
					DynamicGraph.this.repaint();
					try {
						sleep(50);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

	private class MyPanel extends JPanel {

		private Point prev = new Point(0, 0);

		public void paint(Graphics g) {
			//			g.setColor(Color.white);
			//			g.fillRect(0, 0, DynamicGraph.WIDTH, DynamicGraph.WIDTH);
			g.setColor(Color.blue);
			drawGridLines(g);
			g.setColor(Color.RED);
			drawGraph(g);
		}

		public void drawLine(Graphics g, Point.Double p1, Point.Double p2) {
			Point n1 = tc(p1);
			Point n2 = tc(p2);
			g.drawLine(n1.x, n1.y, n2.x, n2.y);
		}

		public void drawGridLines(Graphics g) {
			for(double i = 0; i <= xMax; i+=xStep) {
				for(double j=0; j <= yMax; j+=yStep) { 
					drawLine(g, new Point.Double(0, j), new Point.Double(xMax, j));
				}
				drawLine(g, new Point.Double(i, 0), new Point.Double(i, yMax));
			}			
		}

		public void drawGraph(Graphics g) {
			for(int i = 0; i < values.size() - 1; i++) {
				Point p1 = tc(values.get(i));
				Point p2 = tc(values.get(i + 1));
				((Graphics2D) g).setStroke(new BasicStroke(3));
				g.drawLine(p1.x, p1.y, p2.x, p2.y);
			}
		}

		public Point tc(Point.Double in) {
			return new Point((int) (DynamicGraph.WIDTH * in.x / xMax), (int)(DynamicGraph.HEIGHT - in.y * DynamicGraph.HEIGHT / yMax));  
		}

	}
}
